import jwt from 'jsonwebtoken';

const JWT_SECRET = 'your-secret-key'; // 在实际生产环境中，应该使用环境变量

export const authMiddleware = async (ctx, next) => {
  try {
    const token = ctx.headers.authorization?.split(' ')[1];
    if (!token) {
      ctx.status = 401;
      ctx.body = { error: '未提供认证令牌' };
      return;
    }

    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      ctx.state.user = decoded;
      await next();
    } catch (error) {
      ctx.status = 401;
      ctx.body = { error: '无效的认证令牌' };
    }
  } catch (error) {
    console.error('认证中间件错误:', error);
    ctx.status = 500;
    ctx.body = { error: '认证过程发生错误' };
  }
};

export const generateToken = (user) => {
  return jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
};
